import router from './index'
import $store from '@/plugins/store'
import { subRouteForDynamicRouting } from '@/router'
import { RouteRecordRaw } from 'vue-router'

import { allModulesRoutes } from './modules'
import Route from './entity/Route'

const modules = import.meta.glob('../views/**/*.vue')

/**
 * 动态路由的加载不能给某一个页面触发加载，如果这样会导致直接进入动态的路由会不存在路由
 * 应该给main.ts时就触发，但需要保证有路由信息，而进入动态路由必须已经登录，而登录了肯定有路由
 */
let currentMenus: Route[] = $store.menu.getRouteListPlaneStructure()
function loadRouter(appendList: Route[] = []) {
  const hasRoutes = $store.menu.hasRoutes
  // 获取路由的平面结构（树形->平面）
  console.log('获取平面Menus')
  const currentLoadMenuList = [...currentMenus, ...appendList]
  console.log('平面Menus:', currentLoadMenuList)
  if (!hasRoutes && currentLoadMenuList != null) {
    // 如果路由没有加载，先加载路由
    bindRoute(currentLoadMenuList)
    $store.menu.setRoutesState(true)
    currentMenus = currentLoadMenuList
  }
}
// 重新加载路径（只允许追加）
export function reLoadRouter(appendList: Route[] = []) {
  $store.menu.hasRoutes = false
  loadRouter(appendList)
}

// 动态绑定路由
function bindRoute(menuList: Route[]) {
  const newRoutes = router.options.routes
  menuList.forEach((menu) => {
    const route: RouteRecordRaw = menuToRoute(menu, null)
    // 如果route为空说明该路由信息项是“不可连接组件”的项
    if (route == null) return
    // 看是否有对应的静态子路由需要追加
    if (Object.prototype.hasOwnProperty.call(subRouteForDynamicRouting, route.path)) {
      if (route.children == null) route.children = []
      route.children.push(Reflect.get(subRouteForDynamicRouting, route.path))
    }
    // newRoutes[0] 是layout指定存放的路由位置
    newRoutes[0].children.push(route)
  })
  // 重新添加到路由
  newRoutes.forEach((route) => {
    router.addRoute(route)
  })
  console.log('动态路由加载完成', router)
}
// 菜单对象转成路由对象
function menuToRoute(menu: Route, parentLabel: string): RouteRecordRaw {
  if (menu.component == null || menu.component == '' || menu.path == null || menu.path == '') return null
  const route = {
    name: menu.name,
    path: menu.path,
    // 这里动态路由需要写 ../ 不能@/ ,环境原因
    component: modules[`../views/home${menu.component}${menu.component.indexOf('.vue') >= 0 ? '' : '/index.vue'}`], // () => import('../views/' + menu.component + '/index.vue'),
    meta: { ...menu.meta, parentLabel }
  }
  return route
}

// 初始化路由
loadRouter(allModulesRoutes)
// 通过监听Menu改变事件重新初始化路由
$store.menu.EVENT_MENUS_CHANGE.on(() => reLoadRouter())
